<template>
  <div class="quotation layout">
      <div class="flex">
        <div class="chat">
          <div class="box">
            <div class="lishi" ref="chatlist">
              <!-- <p>历史记录</p> -->
                <div v-if="chatkehuList.length != 0">
                  <div v-for="(item, index) in chatkehuList" :key="index">
                    <div class="kefu-left" v-if="item && item.fromID != uid">
                      <div class="kefuName">智能客服</div>
                      <div v-if="item && String(item.msg).indexOf('image') != '-1'">
                        <!-- <img :src="item.msg" alt="" /> -->
                        <el-image :src="item.msg" :preview-src-list="srcList"></el-image>
                      </div>
                      <p v-else>{{item.msg}}</p>
                    </div>
                    <div class="kehu-right" v-else>
                      <div v-if="item && String(item.msg).indexOf('image') != '-1'">
                        <el-image :src="item.msg" :preview-src-list="srcList"></el-image>
                      </div>
                      <p v-else>{{item.msg}}</p>
                    </div>
                  </div>
                </div>
            </div>
            <div class="chatbox">
              <div class="chat-left">
                <div class="upFile">
                  <input type="file" ref="imagefile" class="file" name="file" accept="image/*" @change="handleuploadFile($event)"/>
                  <img src="../../assets/img/fileIcon.png" class="fileImg"/>
                </div>
                <textarea class="textarea" cols="70" rows="3" ref="kefuinput" v-model="kefuInput"></textarea>
              </div>
              <input v-if="kefuInput == ''" title="不能发送空白信息" class="chat-btn chat-btn-none" type="button" value="发送"/>
              <input v-else class="chat-btn" type="button" value="发送" @click="handleWsSend('text')"/>
            </div>
          </div>
        </div>
      </div>
  </div>
</template>

<script>
import './chat.scss'
import File from './file'
// import axios from "axios";
import store from '../../store'
// import {initkehuWs, wsSend} from './kehuchat'
import { wsSendkf } from '../../request/trade'
import { initkefuWs } from './kefuchat'
// import {wsSendKehu} from '../../request/trade'
import {photoCompress} from './zip'
import {
		mapGetters
	} from "vuex"
import mqtt from 'mqtt'
var client
const options = {
    connectTimeout: 40000,
    clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
    username: "",
    password: "",
    clean: true
}
export default {  
  components: {
    File
  },
  data() {
    return {
      diaVisible: true,
      file: '',
      kefuInput: '',
      chatInput: '上传图片'
    };
  },
  computed: {
    ...mapGetters([
      "chatkehuList",
      "chatkefuList",
      "uid",
      "srcList"
    ])
  },
  watch: {
    chatkehuList: {
      handler(val) {
        // console.log('获取客服信息')
        //console.log(chatdiv.scrollHeight)
        // chatdiv.scrollTop = chatdiv.scrollHeight;
        this.scroll()
      },
      immediate: true,
      deep: true
    }
  },
  mounted () {
    // initkehuWs()
    // initkefuWs()
    // console.log('消息列表', `chating/history/kf1`, `${store.getters.uid}`)
    // wsSend(`chating/history/${store.getters.kid}`, `${store.getters.uid}`)
    let vm = this
    document.onkeydown = function(event) {
					if(event.keyCode == 13) {
						if(vm.kefuInput) {
              vm.handleWsSend('text')						  
            }
            event.preventDefault()
					}
				};
  },
  methods: {
    scroll() {
			setTimeout(()=>{
				var ele = this.$refs.chatlist
				if (ele.scrollHeight > ele.clientHeight) {
          //设置滚动条到最底部
          ele.scrollTop = ele.scrollHeight;
        }
			} ,300)
		},
    dialogClose () {

    },
   
    sendMessage () {},
    handleChat1 () {},
    
    handleWsSend (data) {
      let _data = ''
      if (data == 'text') {
        _data = this.kefuInput
      } else {
        _data = data
      }
      let uid = store.getters.uid
      let kid = store.getters.kid
      let time = new Date().getTime()
      let content = {}
      
      content = {"content":
          {"fromID": uid,"toID": kid,"msg": _data, "time": time}
      }
      if (_data != '') {
        wsSendkf(`chating/customer/${uid}/${kid}`, JSON.stringify(content))
        store.dispatch('user/updateChatList', content)
        this.kefuInput = ''
      }
    },
    handleuploadFile (evt, flg) {
      let data = ''
      let files = Array.prototype.slice.call(evt.target.files)
      let vm = this
      console.log('图片大小', files[0].size/1024)
      let maxSize = 50 *1024 // 限制上床图片大小不超过50k
      

      files.forEach(function (file, i) {
        
        let reader = new FileReader()
        if (file.size/1024 < 10) {
          reader.onload = function (fv) {
            data = fv.target.result
            if (data) {
              console.log('图片长度', data.length)
              
              // vm.dealImage(data, 100, vm.useImg)
              vm.handleWsSend(data)
              vm.$refs.imagefile.value = ''
            }
            // let image = data.split(',')[1]
            vm.chatInput = data
            // console.log('base64', image)
          }
        } else {
          photoCompress(file, {}, function (base64Codes) {
                console.log('输出压缩图片', base64Codes.length)
                vm.handleWsSend(base64Codes)
                vm.$refs.imagefile.value = ''
          });
        }
        

        
        reader.readAsDataURL(file)
        
      })
    },

    handleSubmit () {
      console.log('1')
    }
    
  }
}
</script>

<style scoped>

</style>